package com.yonyou.pmclouds.messagenotice.constructor.impl;

import com.yonyou.pmclouds.basecom.entity.Entity;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.BeanHelper;
import com.yonyou.pmclouds.basecom.util.CommonFieldConst;
import com.yonyou.pmclouds.messagenotice.constructor.itf.IMessageNoticeConstructor;
import com.yonyou.pmclouds.messagenotice.entity.MessageNoticeVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 消息通知内容构造类
 */
@Component
public class MessageNoticeConstructor {

    private Map<String, IMessageNoticeConstructor> constructorMap = new HashMap<>();

    public MessageNoticeVO[] generateNotice(Entity vo) throws BusinessException {
        // 根据单据类型获取具体类型通知内容的生成
        String billType;
        if(vo instanceof MessageNoticeVO){
            billType = ((MessageNoticeVO) vo).getRelateType();
        }else {
            billType = StringUtils.isEmpty(getFieldValue(vo, CommonFieldConst.BILL_TYPE))
                    ? getFieldValue(vo, CommonFieldConst.BILLTYPE)
                    : getFieldValue(vo, CommonFieldConst.BILL_TYPE);
        }
        IMessageNoticeConstructor noticeConstructor = constructorMap.get(billType);
        if(noticeConstructor == null) {
            return null;
        }
        return noticeConstructor.generateNotice(vo);
    }

    public void addConstructor(IMessageNoticeConstructor constructor){
        if(constructor != null) {
            constructorMap.put(constructor.getRelateType(), constructor);
        }
    }

    private String getFieldValue(Entity vo, String fieldName) {
        Object fieldValue = BeanHelper.getProperty(vo, fieldName);
        if (fieldValue == null) {
            return null;
        }
        return (String) fieldValue;
    }
}
